import { constantRoutes } from '@/router'

import Layout from '@/views/layout'

function view (path) {
  return (resolve) => require([`@/views/${path}.vue`], resolve)
}
function filterRouter (routes) {
  return routes.filter((route) => {
    const component = route.component
    if (component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = view(component)
      }
      if (route.children && route.children.length) {
        route.children = filterRouter(route.children)
      }
      return true
    }
  })
}

// 处理数据为 路由要求的属性格式
function getRouterAttr (data) {
  let parents = data.filter(value => value.meta.pid === 0)
  let childrens = data.filter(value => value.meta.pid !== 0)
  let translator = (parents, childrens) => {
    parents.forEach((parent) => {
      childrens.forEach((current, index) => {
        if (current.meta.pid === parent.meta.id) {
          let temp = JSON.parse(JSON.stringify(childrens))
          temp.splice(index, 1)
          translator([current], temp)
          typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [current]
        }
      }
      )
    }
    )
  }
  translator(parents, childrens)
  return parents
}

const permission = {
  state: {
    routes: [],
    addRouters: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRouters = routes
      state.routes = constantRoutes.concat(routes)
    }
  },
  actions: {
    GenerateRoutes ({ commit }, router) {
      return new Promise(resolve => {
        let data = getRouterAttr(router)
        let accessedRouters = filterRouter(data)
        commit('SET_ROUTES', accessedRouters)
        resolve(accessedRouters)
      })
    }
  }
}

export default permission
